package com.example.huajia.wx.controller;

import com.example.huajia.wx.common.util.R;
import com.example.huajia.wx.config.shiro.JwtUtil;
import com.example.huajia.wx.controller.form.GetMessageForm;
import com.example.huajia.wx.controller.form.SendMessageForm;
import com.example.huajia.wx.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("/chat")
@Api("聊天接口")
public class MessageChatController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserService userService;

    @PostMapping("/sendMessage")
    @ApiOperation("发送聊天信息接口")
    public R sendMessage(@Valid @RequestBody SendMessageForm form, @RequestHeader("token") String token){
        int senderId = jwtUtil.getUserId(token);
        String message = form.getMessage();
        Integer acceptId = form.getAcceptId();
        String key = "chat:" + senderId + ":" + acceptId;
        System.out.println("key=" + key);
//        redisTemplate.opsForValue().set(key, message);
        redisTemplate.opsForList().leftPush(key, message);
        return R.ok();
    }

    @PostMapping("/getMessage")
    @ApiOperation("接受聊天信息接口")
    public R getMessage(@Valid @RequestBody GetMessageForm form, @RequestHeader("token") String token){
        int acceptId = jwtUtil.getUserId(token);
        Integer senderId = form.getSenderId();
        String key = "chat:" + senderId + ":" + acceptId;
//        Object message = redisTemplate.opsForValue().get(key);
        Object message = redisTemplate.opsForList().rightPop(key);
        if (message == null){
            return R.ok();
        }
//        redisTemplate.delete(key);
        return R.ok().put("result", message.toString());
    }

    @GetMapping("/getAcceptId")
    @ApiOperation("查询聊天对象id接口")
    public R getAcceptId(@RequestHeader("token") String token){
        Integer friend = jwtUtil.getUserId(token);
        ArrayList<HashMap> acceptId = userService.getAcceptId(friend.toString());
        return R.ok().put("result", acceptId);
    }

    @PostMapping("/haveNew")
    @ApiOperation("查询是否有新消息接口")
    public R haveNew(@Valid @RequestBody GetMessageForm form, @RequestHeader("token") String token){
        Integer acceptId = jwtUtil.getUserId(token);
        Integer senderId = form.getSenderId();
        String key = "chat:" + senderId + ":" + acceptId;
        Boolean haveNew = redisTemplate.hasKey(key);
        return R.ok().put("result", haveNew);
    }
}